import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:jd_shop/net/MallmsService.dart';
import 'package:jd_shop/utils/ToastMsg.dart';
import 'package:jd_shop/utils/Utils.dart';

import '../../event/ProductContentEvent.dart';
import '../../model/GoodsDetailBean.dart';
import '../../net/ShoppingOrderService.dart';
import '../../services/ScreenAdaper.dart';
import '../../widget/BaseLoadind.dart';
import '../../widget/CartNum.dart';
import '../../widget/SwiperWidgetUtils.dart';

class TabGoods extends StatefulWidget {
  Map arguments;

  TabGoods({super.key, required this.arguments});

  @override
  _TabGoodsState createState() => _TabGoodsState();
}

class _TabGoodsState extends State<TabGoods>
    with AutomaticKeepAliveClientMixin {
  late GoodsDetailBean goodsDetail;
  bool isLoading = true;

  //规格
  String goodsSpec = "";

  List<String> bannerList = [];
  var productContentEventListen;

  @override
  void initState() {
    super.initState();
    queryGoodsDetailNet();
    productContentEventListen =
        eventBus.on<ProductContentEvent>().listen((event) {
      attrBottomsheet();
    });
  }

  @override
  void dispose() {
    super.dispose();
    // 取消监听
    productContentEventListen.cancel();
  }

  void queryGoodsDetailNet() {
    var params = HashMap<String, dynamic>();
    params["goodsId"] = this.widget.arguments["goodsId"];
    // params["commonId"] = this.widget.arguments["commonId"];
    MallmsService.queryGoodsDetailNet(params).then((onValue) {
      goodsDetail = onValue;
      isLoading = false;
      goodsSpec =
          goodsDetail.gdsCommon!.commonSpecValueList![0].goodsSpec.toString();
      bannerList = [];
      goodsDetail.goodsImages?.forEach((element) {
        bannerList.add(element.imagesImage);
      });
      setState(() {});
    });
  }

  void attrBottomsheet() {
    showModalBottomSheet(
        context: context,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(
              Radius.circular(10)
          ), // 去掉弧度
        ),
        builder: (context) {
          return StatefulBuilder(builder: (context, setState) {
            return Container(
                height: ScreenAdapter.height(300),
                width: ScreenAdapter.getScreenWidth(),
                padding: EdgeInsets.only(
                    left: ScreenAdapter.width(15),
                    top: ScreenAdapter.width(15),
                    right: ScreenAdapter.width(0)),
                child: Column(children: [
                  Row(
                    //顶部对齐
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Image.network(
                        goodsDetail.gdsCommon!.commonImage.toString(),
                        width: ScreenAdapter.height(80),
                        height: ScreenAdapter.height(80),
                        fit: BoxFit.cover,
                      ),
                      SizedBox(width: ScreenAdapter.width(10)),
                      Container(
                        height: ScreenAdapter.height(80),
                        width: (ScreenAdapter.getScreenWidth() -
                            ScreenAdapter.width(130)),
                        child: Stack(
                          children: [
                            Text(
                              goodsDetail.goodsBases!.goodsName.toString(),
                              maxLines: 2, softWrap: true, // 确保文本自动换行
                              overflow: TextOverflow.ellipsis,
                            ),
                            Positioned(
                              left: 0,
                              bottom: 0,
                              child: Text(
                                  "￥${Utils.formatDouble(goodsDetail.goodsBases!.goodsPrice)}",
                                  style: TextStyle(
                                      fontSize: ScreenAdapter.fontSize(20),
                                      color: Colors.red)),
                            ),
                            Positioned(
                                right: 0,
                                bottom: 0,
                                child: CartNum(
                                    max: goodsDetail.goodsBases!.goodsMaxSale,
                                    countNum: goodsDetail.goodsBases!.goodsNum,
                                    onChangedRemove: (value) {
                                      goodsDetail.goodsBases!.goodsNum = value;
                                    },
                                    onChangedAdd: (value) {
                                      goodsDetail.goodsBases!.goodsNum = value;
                                    })),
                          ],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 10),
                  Row(
                    children: [
                      const Text("规格："),
                      const SizedBox(width: 10),
                      //循环遍历 goodsDetail.gdsCommon.commonSpecValueList  在wrap 中添加 Text
                      SizedBox(
                        width: ScreenAdapter.getScreenWidth() -
                            ScreenAdapter.height(71),
                        child: Wrap(
                            spacing: 8.0, // 设置 Text 小部件之间的水平间距
                            runSpacing: 4.0, // 设置 Text 小部件之间的垂直间距
                            children: goodsDetail
                                .gdsCommon!.commonSpecValueList!
                                .map((value) {
                              return InkWell(
                                child: Container(
                                  padding: const EdgeInsets.only(
                                      left: 10, right: 10, top: 4, bottom: 4),
                                  margin: const EdgeInsets.only(bottom: 10),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(20),
                                    color:
                                        goodsSpec == value.goodsSpec.toString()
                                            ? const Color(0xFFfcf0f0)
                                            : Colors.black12,
                                    border: Border.all(
                                        color: goodsSpec ==
                                                value.goodsSpec.toString()
                                            ? Colors.red
                                            : Colors.transparent,
                                        width: 1),
                                  ),
                                  child: Text(
                                    value.goodsSpec.toString(),
                                    //#f4f4f1
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: goodsSpec ==
                                              value.goodsSpec.toString()
                                          ? Colors.red
                                          : Colors.black38,
                                    ),
                                  ),
                                ),
                                onTap: () {
                                  setState(() {
                                    goodsSpec = value.goodsSpec.toString();
                                  });
                                },
                              );
                            }).toList()),
                      )
                    ],
                  ),
                  const SizedBox(height: 10),
                  Expanded(
                      flex: 1,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          InkWell(
                            child: Container(
                              height: ScreenAdapter.height(40),
                              width: (ScreenAdapter.getScreenWidth() -
                                      ScreenAdapter.width(40)) /
                                  2,
                              margin: EdgeInsets.only(
                                  bottom: ScreenAdapter.width(10)),
                              decoration: BoxDecoration(
                                color: Colors.blue,
                                borderRadius: BorderRadius.circular(20),
                              ),
                              alignment: Alignment.center,
                              child: const Text("加入购物车",
                                  style: TextStyle(color: Colors.yellow)),
                            ),
                            onTap: () {
                              ShoppingOrderService.addCartGoodsNet(
                                      goodsDetail.goodsBases!.goodsId,
                                      goodsDetail.goodsBases!.goodsNum)
                                  .then((onValue) {
                                ToastMsg.show("加入成功！");
                                //关闭弹窗
                                Navigator.of(context).pop();
                              });
                            },
                          ),
                          SizedBox(
                            width: ScreenAdapter.width(10),
                          ),
                          InkWell(
                            child: Container(
                              height: ScreenAdapter.height(40),
                              width: (ScreenAdapter.getScreenWidth() -
                                      ScreenAdapter.width(40)) /
                                  2,
                              margin: EdgeInsets.only(
                                  bottom: ScreenAdapter.width(10)),
                              decoration: BoxDecoration(
                                color: Colors.blue,
                                borderRadius: BorderRadius.circular(20),
                              ),
                              alignment: Alignment.center,
                              child: const Text("立即购买",
                                  style: TextStyle(color: Colors.white)),
                            ),
                            onTap: () {
                              ToastMsg.show("点击购买");
                              //关闭弹窗
                              Navigator.of(context).pop();
                            },
                          ),
                        ],
                      )),
                ]));
          });
        });
  }

  initView() {
    if (isLoading) {
      return Container();
    }
    return Container(
        child: ListView(
      children: [
        defaultSwiperWidget(bannerList, aspectRatio: 1 / 1),
        Container(
          color: Colors.white,
          padding: EdgeInsets.all(ScreenAdapter.width(10)),
          child: Text(
            goodsDetail.goodsBases!.goodsName,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: ScreenAdapter.fontSize(20),
              color: Colors.black,
            ),
          ),
        ),
        Container(
          color: Colors.white,
          padding: EdgeInsets.all(ScreenAdapter.width(10)),
          child: Text(
            goodsDetail.goodsBases!.goodsName,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: ScreenAdapter.fontSize(16),
              color: Colors.black54,
            ),
          ),
        ),
        Container(
          padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
          color: Colors.white,
          height: ScreenAdapter.height(40),
          child: Row(children: [
            Text(
              "￥${Utils.formatDouble(goodsDetail.goodsBases!.goodsPrice)}",
              style: TextStyle(
                fontSize: ScreenAdapter.fontSize(20),
                color: Colors.red,
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(
                child: const Text(""),
              ),
            ),
            const Text("原价：",
                style: TextStyle(
                  color: Colors.black54,
                )),
            Text(
              "￥${Utils.formatDouble(goodsDetail.goodsBases!.goodsMarketPrice)}",
              style: const TextStyle(
                decoration: TextDecoration.lineThrough,
                color: Colors.black54,
              ),
            )
          ]),
        ),
        InkWell(
          child: Container(
            padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
            color: Colors.white,
            height: ScreenAdapter.height(40),
            margin: const EdgeInsets.only(top: 10),
            child: Row(children: [
              Text(
                "规格：${goodsDetail.goodsBases!.goodsSpec.toString()}",
                style: TextStyle(
                    color: Colors.black, fontSize: ScreenAdapter.fontSize(14)),
              ),
            ]),
          ),
          onTap: () {
            attrBottomsheet();
          },
        ),
        Container(
          padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
          color: Colors.white,
          height: ScreenAdapter.height(40),
          margin: const EdgeInsets.only(top: 10),
          child: Row(children: [
            Text(
              "运费：",
              style: TextStyle(
                  color: Colors.black, fontSize: ScreenAdapter.fontSize(14)),
            ),
            Text(goodsSpec)
          ]),
        ),
        const SizedBox(height: 10),
      ],
    ));
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);
    return BaseLoadind(
        isLoading: isLoading,
        child: Container(
          margin: EdgeInsets.only(bottom: ScreenAdapter.height(55)),
          child: initView(),
        ));
  }

  @override
  bool get wantKeepAlive => true;
}
